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:
[ruby]
# config/environments/development.rb
Demo::Application.configure do
[…]
config.json_url = "http://www.domain.com"
[…]
end
[/ruby]
[ruby]
# config/environments/test.rb
Demo::Application.configure do
[…]
config.json_url = "http://test.domain.com"
[…]
end
[/ruby]
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:
[ruby]
# config/environments/application.rb
Demo::Application.configure do
config.my_app = ActiveSupport::OrderedOptions.new
end
[/ruby]
[ruby]
# config/environments/development.rb
Demo::Application.configure do
[…]
config.my_app.json_url = "http://www.domain.com"
[…]
end
[/ruby]
[ruby]
# config/environments/test.rb
Demo::Application.configure do
[…]
config.my_app.json_url = "http://test.domain.com"
[…]
end
[/ruby]
Now you can do the following in the Rails console:
[ruby]
$ rails console
>> Demo::Application.config.my_app.json_url
"http://www.domain.com"
>>
[/ruby]
[ruby]
$ rails console test
>> Demo::Application.config.my_app.json_url
"http://test.domain.com"
>>
[/ruby]
Now your Rails application will have access to all the configuration you need.