Updated: Rails3 Custom Environment Variables
A while back, I wrote a blog post on adding custom environment variables to Rails3.
This has gotten much easier with a change made by Jose Valim back in March.
The change allows you to create your own custom configuration variables like so:
# config/environments/development.rb Demo::Application.configure do [...] config.json_url = "http://www.domain.com" [...] end
# config/environments/test.rb Demo::Application.configure do [...] config.json_url = "http://test.domain.com" [...] end
This allows you to add any configuration variables you want to your Rails app. What if you have a bunch of configuration values? You don’t want to pollute your config.* namespace. Wouldn’t it be helpful to have config.my_app.json_url and config.my_app.other_url?
That’s easy enough:
# config/environments/application.rb Demo::Application.configure do config.my_app = ActiveSupport::OrderedOptions.new end
# config/environments/development.rb Demo::Application.configure do [...] config.my_app.json_url = "http://www.domain.com" [...] end
# config/environments/test.rb Demo::Application.configure do [...] config.my_app.json_url = "http://test.domain.com" [...] end
Now you can do the following in the Rails console:
$ rails console >> Demo::Application.config.my_app.json_url "http://www.domain.com" >>
$ rails console test >> Demo::Application.config.my_app.json_url "http://test.domain.com" >>
Now your Rails application will have access to all the configuration you need.