Michael Giovanni Pumo Michael Giovanni Pumo - 5 months ago 27x
Ruby Question

Where can I store site-wide variables in Rails 4?

I am new to Rails and come from a ColdFusion background, where we would store global / site-wide variables in the 'application' scope. This persists the variable across any view or controller. Does Rails 4 have an equivalent functionality for this type of thing?

The site-wide variable won't typically change often so it doesn't need protecting in any way.

For example, in my situation, I want to store the website's domain name. One for testing and one for live environments. Localhost for development and xxxxxx.com for production.

Any tips or pointers would help. I have Googled this extensively and solutions seem to be far too complicated to achieve what seems to be such a trivial task. What's the best elegant solution for Rails 4?


The simplest, basic and default way is to use the Rails.application.config store.

Rails.application.config.my_config = 'foo'

You can assign a config in your environment:

# application.rb
module MyApp
  class Application < Rails::Application
    config.my_config = 'foo'

and read it with

# => 'foo'

This approach works well for very simple applications, but if you want something more advanced there are several gems available.

I'm currently using SimpleConfig. The main advantages are:

  • per-environment configuration. You can configure default configurations for the application, then override defaults with environment specific configurations
  • local.rb file for custom overrides
  • capistrano-like configuration style
  • it works nicely with the dotenv gem, very useful to avoid storing sensitive credentials in your repo.