user1611830
user1611830

Reputation: 4867

where to put configuration constant in rails

I have to use a constant inside my /app/config/environments/production.rb. I'd like to put it somewhere as configuration constant. So I tried to put it inside an initializer file, but /app/config/environments/production.rb seems to be loaded before. Then I tried to put my constant inside Rails::Initializer.run do |config|... inside the /app/config/environment.rb, but /app/config/environments/production.rb still seems to be loaded before. Where can I put propermy this constant as a config constant so that /app/config/environments/production.rb recognizes it ?

Upvotes: 1

Views: 1049

Answers (1)

epsilones
epsilones

Reputation: 11629

Let's make it clear what is the path you walk through to your app loads the initilization files. You must have in mind this :

When you run rails s (from your app/script/rails file) that runs rails server,

  • your app boot.rb file (which mainly deals with gems loading) is required and then your console args (here the server alias s) requirement is passed to the rails railties/lib/rails/command.rb file (which is in the rails source code).

  • There, your app config/application.rb is required. Then, the Server class is instantiated and you are thrown in railties/lib/rails/command/server.rb file. In fact, the Server class inhererits from Rack::Server, so a rails app is rack app ! So, you'll find a config.ru file in your rails app and this loads the config/environment.rb file.

The config/environment.rb file does two things

  • requiring your app config/applcation.rb, that loads the proper rails framework.( For info, you'll find in your app application.rb the Application class that inherits from Rails::Application, which inherits itself from the Rails::Engine, which inherits from a Rails::Railtie class)

  • calling the initialize! bang method, that loads the config/environment/*.rb files, and then processes all the initializers process (more precisely, the initializers methods are defined in the railties/lib/rails/engine.rb) file. So, now, taking that into account, you should be able to define properly your constants.

To better understand the intialization process, I recommand you this great railscast, which mainly inspired this answer.

Upvotes: 3

Related Questions