How do I access a Rails configuration value during runtime?

Ruby on-Rails

Ruby on-Rails Problem Overview


I'm using Rails 2.3.x. I would like a small section of code to run if and only if the config.cache_classes is true. By default, that's true for production and false for development.

How do I access the value of config.cache_classes from outside of my environment.rb, development.rb, and production.rb files? It's easy to tell if we are in production or development, Rails.env will give us the answer. But there's no guarantee the developer hasn't set config.cache_classes = true in development.

I certainly understand that you do not generally want to run separate code paths in development and production. In this particular instance, we are simply not performing some work on startup; if we need to perform it later, we will do so, both in development and production.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

For Rails 2, you can do:

Rails.configuration.cache_classes

If you ever switch to Rails 3, it'll be different; you can access the same value with:

Rails.application.config.cache_classes

Solution 2 - Ruby on-Rails

Depending on where you are in a module, you may need to access the root namespace. This should provide access from anywhere in a universal way for rails 3+:

::Rails.application.config

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChrisInEdmontonView Question on Stackoverflow
Solution 1 - Ruby on-RailsmolfView Answer on Stackoverflow
Solution 2 - Ruby on-RailskrossView Answer on Stackoverflow