Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: how to detect if the application is running in server mode for multiple different environment?

I have an app that runs on multiple servers: - locally on dev machines - on heroku - on a specific server with Passanger on Nginx

I am trying to launch a particular code (loading some REDIS keys) that is only required if the web server is launched.

I have done quite a bit of digging, and the nicest solution I found was to execute my code in an initializer with:

if defined?(Rails::Server)
   #my code
end

This works well locally, but it seems that Rails::Server never gets defined either on Heroku or Passanger.

I need a solution that works in every case, please help, this is really important.

Thanks,

Alex

ps: I am running Rails 3.0.4, Ruby 1.8.7

like image 903
Alex Avatar asked Apr 09 '11 11:04

Alex


People also ask

How does Rails know which environment?

Rails reads the current environment from the operating system's environment variables by checking the following in order of priority: Get the value of the RAILS_ENV environment variable by calling ENV["RAILS_ENV"] If the above is nil, then get ENV["RACK_ENV"] If the above is nil, then make it equal to "development"

How do I run a Rails server on a different port?

Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .

What happens when we run Rails server?

One of the things rails server does is that it loads all the dependencies/gems required by your Rails app, or at least sets them up to be auto-loaded later when they are needed. This is sometimes called "booting" or loading the "Rails environment".

What is application RB in Rails?

The configuration file config/application. rb and environment-specific configuration files (such as config/environments/production. rb ) allow you to specify the various settings that you want to pass down to all of the components. For example, you could add this setting to config/application.rb file: config.


1 Answers

Putting code in your config.ru file might be a more robust way of detecting server mode across different types of servers (Unicorn/Passenger/Rails::Server/etc).

e.g., in rails-root/config.ru:

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

# ADD this line and read the value later:
ENV['server_mode'] = '1'

require ::File.expand_path...
like image 167
Jordan Brough Avatar answered Nov 02 '22 23:11

Jordan Brough