For Rails, how to access or print out config variables (as experiment or test / debugging)

Ruby on-RailsRuby on-Rails-3

Ruby on-Rails Problem Overview


For example, in config/environments/production.rb in a Rails 3 app, there is

config.serve_static_assets = false

and many variables. How can they be all printed out as a whole (perhaps in an object, instead of specifying each one-by-one) (print out in a view, such as FooController#index), just for looking into what types of values are available and to see what they are set to?

Also, how to print out the values in the .yml files (as a hash and/or in some config object?) and in config/initializers, such as for

MyAppFoo::Application.config.session_store :active_record_store

I found that we can print out the content of

ActiveRecord::Base.configurations

but not

ActionController::Base.configurations

are there ways to print out all info of the MVC components?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Most of the Rails config stuff can be accessed through:

Rails.application.config.<your_variable>

With regards to printing out the values of .yml files in config, you'd have to do that yourself becuase Rails will only load up the values for the current environment from database.yml, and any custom yml config files will be just that - custom. Here's one way you could load them all up...

all_configs = []
Dir[Rails.root.join("config/*.yml")].each {|f| all_configs << YAML.load_file(f) }

With regards to settings set in initializers, if it's a Rails config option (such as the session store which you've given as an example), then it will be available through Rails.application.config. If not, (for example configuration for a gem) then you will have to manually find those settings from the gem classes.

Solution 2 - Ruby on-Rails

You can also use AppName::Application.config (where AppName is the name of your application) to access the Rails::Application::Configuration object.

$ AppName::Application.config == Rails.application.config
true

Solution 3 - Ruby on-Rails

Like idlefingers pointed out, for newer versions of rails, Rails.application.config.my_variable should get you what you're looking for.

However, if that doesn't work because you're stuck with an older version of Rails (2.3, etc) you can use the ENV constant, like so: ENV['my_variable']

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
QuestionnonopolarityView Question on Stackoverflow
Solution 1 - Ruby on-RailsidlefingersView Answer on Stackoverflow
Solution 2 - Ruby on-RailsDennisView Answer on Stackoverflow
Solution 3 - Ruby on-RailsbrooxView Answer on Stackoverflow