3

Rails3 Custom Environment Variables

Posted by Jason Noble on 02/14/2011 in ruby, ruby on rails |

I recently saw a question on Stack Overflow regarding custom variables that have different values based on which environment you are running for Rails.

It turns out it’s very easy to accomplish.

[ruby]
# config/initializers/configuration.rb
class Configuration
class << self
attr_accessor :json_url
end
end
[/ruby]

This gives you access to a Rails variable called Configuration.json_url. Now we just need to initialize this value in our environment files.

[ruby]
# config/environments/development.rb
# Put this inside the ______::Application.configure block
config.after_initialize do
Configuration.json_url = "http://test.domain.com"
end
[/ruby]

[ruby]
# config/environments/test.rb
config.after_initialize do
Configuration.json_url = "http://www.domain.com"
end
[/ruby]

Now you can test it in the Rails console.

[text]
$ rails console
>> Configuration.json_url
"http://test.domain.com"
>>
[/text]

[text]
$ RAILS_ENV=production rails console
>> Configuration.json_url
"http://www.domain.com"
>>
[/text]

Now your Rails app has access to these variables, so you can use them in your Controllers, Models or Views as needed.

3 Comments

Comments are closed. Would you like to contact the author directly?

Copyright © 2008-2024 Jason Noble's Technical Adventures All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.5, from BuyNowShop.com.